﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
    internal class TcpIpClient
    {
        private TcpClient tcpClient;
        private NetworkStream stream;
        private Action<string> logAction;
        public event Action<string> DataReceived;


        public TcpIpClient(Action<string> logAction)
        {
            this.logAction = logAction;
        }
        

        public bool Connect(string ipAddress, int port)
        {
            try
            {
                tcpClient = new TcpClient(ipAddress, port);
                stream = tcpClient.GetStream();
                Log("Connected to server.");
                Task.Run(() => ReceiveData());
                return true;
            }
            catch (Exception ex)
            {
                Log($"Exception: {ex.Message}");
                return false;
            }
        }

        public void Send(string data)
        {
            byte[] dataBytes = Encoding.ASCII.GetBytes(data);
            stream.Write(dataBytes, 0, dataBytes.Length);
            Log($"Data sent: {data}");
        }

        private async Task ReceiveData()
        {
            byte[] buffer = new byte[1024];
            int bytesRead;

            while (true)
            {
                bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                if (bytesRead == 0) break;

                string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Log($"Data received: {receivedData}");

                // 触发 DataReceived 事件，将接收到的数据传递出去
                DataReceived?.Invoke(receivedData);
            }
        }

        public void Disconnect()
        {
            tcpClient.Close();
            Log("Disconnected from server.");
        }

        private void Log(string message)
        {
            logAction?.Invoke(message);
        }
    }
}
